題目:爬樓梯,往上爬一次可爬1步或是2步,不可往下走
輸入:樓梯階數
輸出:印出可能的步數,及總共的排列可能數目
#include <iostream>
using namespace std;
int len = 0,n =0 ,sum = 0,*step;
void printSum() {
cout << "走法 = ";
for (int i = 0; i < len; i++)cout <<step[i]<<" ";
cout <<endl;
}
void compute(int stair) {
if (stair < 0) return;
if (stair == 0) {
printSum();
sum++;
return;
}
for (int i = 1; i <= 2; i++) {
step[len] = i;
len++;
compute(stair - i);
len--;
}
}
int main () {
cout << "請輸入樓梯階層";
cin >> n;
if (n!=0){
step = new int[n];
compute(n);
cout << "共有 :"<< sum << "走法"<< endl;
}
}